package com.qf.personal.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.common.base.exception.ServiceException;
import com.qf.common.base.result.RespResult;
import com.qf.common.base.result.ResultCode;
import com.qf.personal.entiy.Car;
import com.qf.personal.entiy.CarManage;
import com.qf.personal.mapper.CarManageMapper;
import com.qf.personal.mapper.CarMapper;
import com.qf.personal.mapper.IndexMapper;
import com.qf.personal.service.CarService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.beans.Transient;
import java.util.List;

@Service
public class CarServiceImpl implements CarService {
    @Resource
    private CarMapper carMapper;
    @Resource
    private CarManageMapper carManageMapper;
    @Resource
    private IndexMapper indexMapper;

    @Override
    @Transient
    public RespResult<String> addUseCar(Car car) {
        int a = carMapper.insert(car);
        if (a != 0) {
            return RespResult.success("新增成功");
        } else {
            throw new ServiceException(ResultCode.SYS_ERROR);
        }
    }

    @Override
    public RespResult<List<CarManage>> selectCar() {
        QueryWrapper<CarManage> qw = new QueryWrapper<>();
        qw.select("car_brand", "car_sort_id", "car_id").eq("status", 1).eq("car_status", 1);
        List<CarManage> c = carManageMapper.selectList(qw);
        if (!ObjectUtils.isEmpty(c)) {
            return RespResult.success(c);
        } else {
            throw new ServiceException(ResultCode.SYS_ERROR);
        }
    }

    @Override
    public RespResult<List<Car>> selectAll(int eId) {
        QueryWrapper<Car> qw = new QueryWrapper<>();
        qw.select("*").eq("status", 1);
        List<Car> c = carMapper.selectList(qw);
        if (!ObjectUtils.isEmpty(c)) {
            return RespResult.success(c);
        } else {
            throw new ServiceException(ResultCode.SYS_ERROR);
        }

    }

    @Override
    public RespResult<List<Car>> searchCar(Car car) {
        List<Car> list = carMapper.searchCar(car);
        if (!ObjectUtils.isEmpty(list)) {
            return RespResult.success(list);
        } else {
            throw new ServiceException(ResultCode.SYS_ERROR);
        }
    }

    @Override
    @Transactional
    public RespResult<String> deleteById(Long id) {
        int a = carMapper.deletById(id);
        try {
            if (a == 1) {
                int b = indexMapper.delete(id);
                if (b == 1) {
                    return RespResult.success("删除成功");
                }
            }
        } catch (ServiceException se) {
            throw new ServiceException(ResultCode.SYS_ERROR);
        }
        return null;
    }
}
